package com.karst87.sqlite.study
{
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;

	internal class TableDealer
	{
		private var sqlConn : SQLConnection = null ;
		public function TableDealer( $sqlConn : SQLConnection )
		{
			sqlConn = $sqlConn ;
			createSqlState() ;
		}

		private var sqlState : SQLStatement = null ;
		private function createSqlState() : void
		{
			if( sqlState == null )
				sqlState = new SQLStatement() ;
			sqlState.sqlConnection = sqlConn ;
			sqlState.addEventListener( SQLEvent.RESULT, resultHandler ) ;
			sqlState.addEventListener( SQLErrorEvent.ERROR, errorHandler ) ;
		}
		
		private var sql : String = "" ;
		
		/////////////////////////////////////////////////////////////
		//
		// 创建数据表
		//
		/////////////////////////////////////////////////////////////
		public function createTabel() : void
		{
			sql = 
				"CREATE TABLE IF NOT EXISTS " +
				"USER(" +
				"ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
				"FIRSTNAME TEXT, " +
				"LASTNAME TEXT, " +
				"SALARY NUMERIC CHECK (SALARY>0)" +
				")" ;
			sqlState.text = sql ;
			sqlState.execute() ;
		}
		
		
		
		public function insertData( $firstName : String, $lastName : String,
									$salary : Number ) : void
		{
			sql = 
				"INSERT INTO USER " +
				"(FIRSTNAME, LASTNAME, SALARY) " +
				"VALUES " +
				"('" +
				$firstName + "','" +
				$lastName + "'," +
				$salary +
				")" ;
			sqlState.text = sql ;
			sqlState.execute() ;
		}
		
		public function searchData( $column : String = "", $limit : String = "" ) : String
		{
			sql = 
				"SELECT * FROM USER" ;
			sqlState.text = sql ;
			sqlState.execute() ;
			return "" ;
		}
		
		
		
		
		private function resultHandler( $event : SQLEvent ) : void
		{
			trace( $event.target["text"] ) ;
			trace( "Deal Table Successfully" ) ;
			
			( sqlState.getResult().data.length )
		}
		
		private function errorHandler( $event : SQLErrorEvent ) : void
		{
			trace( "Error" ) ;
			trace( "Error Message: " + $event.error.message ) ;
			trace( "Error Details: " + $event.error.details ) ;
		}
	}
}